package com.apkcore.flowlib.flow

/**
 * @author chanehao
 * @date 2023/03/08
 * @apiNote
 */

interface Chain {
    suspend fun proceed(request: Request): Request
}

class RealChain<T>(
    private val interceptors: List<Interceptor<T>>, private val index: Int,
    private val feedbackCollector: MutableList<T>,
) : Chain {
    override suspend fun proceed(request: Request): Request {
        if (index >= interceptors.size || !request.resultSuccess) {
            // 所有拦截器都已经执行完毕
            return request
        }

        // 取出当前拦截器
        val interceptor = interceptors[index]

        // 创建一个新的 RealChain，维护 index + 1
        val nextChain = RealChain(interceptors, index + 1, feedbackCollector)

        // 调用当前拦截器的 intercept 方法
        val modifiedRequest = interceptor.intercept(nextChain, request)

        // 传递反馈信息
        feedbackCollector.add(interceptor.feedback() ?: return modifiedRequest)

        return modifiedRequest
    }
}